<template>
  <div class="setting-content inside-comment">
    <h2 class="setting-header">
      <strong>课程内容</strong>
      <p><span>当前章节：</span>{{query.chapterName}}</p>
    </h2>
    <div class="top-info">
      <el-button type="primary" @click="uploadVisible = true">添加内容</el-button>
    </div>
    <!-- 资源列表 -->
    <RuifoxTable
      v-loading="tableLoading"
      v-model:tableData="contentData"
      :field-list="fieldList"
      :lazy="true"
    >
      <!-- 创建时间  -->
      <template #createTime="{ element }">
        <span>{{ dayjs(element.createTime).format("YYYY-MM-DD hh:mm") }}</span>
      </template>
      <template #fileType="{ element }">
        <span>{{element.fileType}}</span>
      </template>
      <template #options="{ element }">
        <div class="table-td-option unmover">
          <el-button
            type="primary"
            link
            @click="preview(element)"
          >
            预览
          </el-button>
          <el-button
            type="danger"
            link
            @click="remove(element)"
          >
            删除
          </el-button>
        </div>
      </template>
    </RuifoxTable>
    <div class="img-list">
      <img v-if="coverImageUrl" :src="coverImageUrl" alt="">

    </div>
    <!-- 上传文件 -->
    <el-dialog v-model="uploadVisible" title="文件上传" width="550px" class="preview-dialog">
      <el-form :model="saveResourceForm" label-width="80px">
        <el-form-item label="上传文件" prop="fileId">
          <el-button type="primary" @click.stop="showFilesUpload = true">选择文件</el-button>
          <div class="file-name" v-if="fileName && fileName != ''">{{fileName}}</div>
        </el-form-item>
        <!-- 暂只做了mp4格式的封面图获取，其他格式暂不支持 -->
        <el-form-item label="封面图" prop="pid" v-if="saveResourceForm.fileType == 'video/mp4'">
          <div class="form-img" @click="handleUploadLogo">
            <div class="has-img" v-if="saveResourceForm.coverImg">
              <img :src="saveResourceForm.coverImg" alt="">
              <span > 
                <el-icon @click.stop="handlePreviewThumb"><ZoomIn /></el-icon>
                <el-icon @click.stop="handleRemoveImg"><Delete /></el-icon>
              </span>
            </div>
            <el-icon v-else>
              <Plus />
            </el-icon>
          </div>
          
        </el-form-item>
        <el-form-item label="视频图片" v-if="saveResourceForm.fileType == 'video/mp4'">
          <el-image
            class="img-container"
            style="width: 150px; height: 100px;"
            :src="fileList[0].url"
            :zoom-rate="1.2"
            :max-scale="5"
            :min-scale="0.2"
            :preview-src-list="srcList"
            show-progress
            @switch="handleSwitch"
            @close="hideButton"
            :initial-index="0"
            fit="cover"
            ref="imageRef"
          />
          <!-- 自定义按钮（隐藏） -->
          <el-button
            id="custom-preview-button"
            style="display: none;"
            @click="getPreviewImage"
            type="primary"
          >
            设为封面图
          </el-button>
        </el-form-item>
        <el-form-item label="文件名称" prop="pid">
          <el-input placeholder="输入文件名称" v-model="saveResourceForm.name"></el-input>
        </el-form-item>
        <!-- <el-form-item label="说明" prop="description">
          <el-input placeholder="输入说明" v-model="saveResourceForm.description"></el-input>
        </el-form-item> -->
        
      </el-form>
      <template #footer>
        <span class="dialog-footer"> 
          <el-button @click="cancelResource">取消</el-button>
          <el-button type="primary" @click="saveResource">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 预览内容对话框 -->
    <el-dialog v-model="previewVisible" title="文件预览" width="1000px" class="preview-dialog">
      <el-scrollbar height="540px">

        <!-- 判断文件类型，对应显示 -->
        <img v-if="previewInfo.type == '图片'" :src="previewInfo.src" alt="" class="preview-img">
        <videoPlay
          v-if="previewInfo.type == 'mp4'"
          v-bind="videoOptions"
          :src="previewInfo.src"
        ></videoPlay>
        <iframe
          v-if="previewInfo.type === 'document'"
          :src="previewInfo.src"
          width="100%"
          height="600px"
          frameborder="0"
        >
          <p>您的浏览器不支持预览此文档。</p>
        </iframe>
        <vue-office-pptx style="width: 100%" v-if="previewInfo.type == 'pptx'" :src="previewInfo.src"  @error="errorHandler"/>
        <vue-office-docx v-if="previewInfo.type == 'docx'" :src="previewInfo.src" />
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="previewVisible = false">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 缩略图预览 -->
    <el-dialog v-model="thumbDialog" width="60%">
      <div style="width: 100%">
        <img :src="saveResourceForm.coverImg" alt="Preview Image" style="width: 100%; height: auto; object-fit: cover" />
      </div>
    </el-dialog>
    <!-- 文件上传  -->
    <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :isPublic="true" @getFileList="insertFiles" :isToJpg="true" :limit="10"></FilesUpload>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import dayjs from "dayjs";
import { useRoute } from "vue-router";
import { videoPlay } from 'vue3-video-play'
import 'vue3-video-play/dist/style.css'
import VueOfficePptx from "@vue-office/pptx";
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getReferencedTypeResourcesRefer, createRefer } from '@/api/resource'
import { ZoomIn, Plus } from '@element-plus/icons-vue'
import { FilesUpload } from "@ruifox-cms/components"

const route = useRoute(); 
const query = ref(route.query); 
const contentData = ref([])
console.log("query",query.value);
//课程类型和资源管理这边字段对不上 重新修改
if(query.value.type == "LESSON") { 
  query.value.type = "COURSE(1,COURSE)"
} else if(query.value.type == "TEST") {
  query.value.type = "CHAPTER(2,CHAPTER)"
} else if(query.value.type == "QUIZ") {
  query.value.type = "EXAM(3,EXAM)"
}

const uploadVisible = ref(false)
//保存资源到本系统
const videoSrc = ref("");
const defaultSaveResourceForm = {
  dataIds: [],
  referenceType: query.value.type,
  referenceId: query.value.chapterId,
  sortOrder: 0,
};
const saveResourceForm =  ref({ ...defaultSaveResourceForm });

//根据章节id获取资源列表
const resourceForm = {
  referenceType: query.value.type,
  referenceId: query.value.chapterId,
}

const getResourceList = async () => {
  console.log("resourceForm",resourceForm);
  
  const res = await getReferencedTypeResourcesRefer(resourceForm);
  if (res.code === 20000 && res.data) {
    contentData.value = res.data;
  }
};

//文件保存到考试系统
const saveResource = async () => {
  // console.log("saveResourceForm.value",saveResourceForm.value);
  // saveResourceForm.value.dataIds = saveResourceForm.value.dataIds.join(",")
  if(Array.isArray(saveResourceForm.value.dataIds)){
    saveResourceForm.value.dataIds = saveResourceForm.value.dataIds.map(item => item.id).join(",");
  }
  // saveResourceForm.value.dataIds = saveResourceForm.value.dataIds.join(",");
  const res = await createRefer(saveResourceForm.value);
  if (res.code === 20000) {
    ElMessage.success("上传成功")
    showFilesUpload.value = false;
    uploadVisible.value = false;
    getResourceList();
  }
};

// 附件上传
const showFilesUpload = ref(false)
const resourceFormList = ref([])
const fileName = ref("")
const fileUrl = ref("")
const insertFiles = (filesList,res) => {
  console.log("filesList",filesList);
  console.log("res",res);
  
  resourceFormList.value = filesList.map(item => {
    return {
      resourceData: {
        title: item.name,
        url: item.url,
        uid: item.uid,
      },
      needUpload: item.needUpload,
      tagList: item.tagList || [],
    }
  })
  console.log("resourceFormList.value",resourceFormList.value);
  fileName.value = resourceFormList.value[0].resourceData.title
  fileUrl.value = resourceFormList.value[0].resourceData.url
  saveResourceForm.value.dataIds = res
  if (resourceFormList.value == 1) {
    createImgList()
  }
  // addInstanceForm.value.coverImg =  resourceFormList.value[0].resourceData.url
}
// const handleUpload = async () => {
//   showFilesUpload.value = true
//   console.log("点击上传图片");
//   console.log("showFilesUpload.value",showFilesUpload.value);
  
// };

// const handleRemoveImg = () => {
//   addInstanceForm.value.coverImg =  [""]
// };
// 预览缩略图
const thumbDialog = ref(false)
const handlePreviewThumb = () => {
  thumbDialog.value = true
}
// 移除缩略图
const handleRemoveImg = () => {
  saveResourceForm.value.coverImg = ''
}

// 当前预览的图片索引
const currentIndex = ref(0);

// el-image 的引用
const imageRef = ref(null);

// 监听图片切换事件
const handleSwitch = (index) => {
  currentIndex.value = index;
};
const hideButton = () => {
  const customButton = document.getElementById('custom-preview-button');
  if (customButton) {
    customButton.style.display = 'none';
  }
};
// 获取当前预览的图片
const getPreviewImage = () => {
  const currentImageUrl = srcList.value[currentIndex.value];
  console.log('当前预览的图片:', currentImageUrl);
  saveResourceForm.value.coverImg = currentImageUrl;

};

// 将自定义按钮注入到预览弹窗中
const injectCustomButton = () => {
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.addedNodes.length > 0) {
        // 查找预览弹窗的容器
        const previewContainer = document.querySelector('.el-image-viewer__wrapper');
        if (previewContainer) {
          // 显示自定义按钮
          const customButton = document.getElementById('custom-preview-button');
          if (customButton) {
            customButton.style.display = 'block';
          }
        }
      }
    });
  });

  // 监听 body 的 DOM 变化
  observer.observe(document.body, { childList: true, subtree: true });
};

const errorHandler = () => {
  console.log("渲染失败")
}

//视频抓取封面图
const coverImageUrl = ref("");
const fileList = ref([])
const srcList = ref([])
const drawVideo = (vdo) => {
    return new Promise((resolve) => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        canvas.width = vdo.videoWidth;
        canvas.height = vdo.videoHeight;
        ctx.drawImage(vdo, 0, 0, canvas.width, canvas.height);
        canvas.toBlob((blob) => {
            resolve({
                blob,
                url: URL.createObjectURL(blob)
            });
        })
    })
}
//截图
const captureFrame = (time) => {
    return new Promise((resolve) => {
        const video = document.createElement("video");
        video.autoplay = true;
        video.currentTime = time;
        video.crossOrigin = "anonymous"; // 避免跨域问题
        video.src = videoSrc.value;
        console.log("video.videoWidth",video.videoWidth);
        console.log("video.videoHeight",video.videoHeight);
        
        video.oncanplay = async () => {
            const frame = await drawVideo(video);
            resolve(frame);
        }
    })
}
//视频按时间截取视频图片
const video = document.createElement("video");
const createImgList = async () => {
  video.src = videoSrc.value;
  // 视频加载完成后，才能获取到视频的时长
  video.onloadedmetadata = async () => {
    console.log("视频加载完成");
    const duration = video.duration; // 视频总时长
    const intervalPercent = duration * 0.25; // 每 5% 的时间间隔
    let captureTimes = []; // 存储需要截图的时间点
    // 前 5 秒每秒抓取一次
    for (let i = 0; i < 5; i++) {
        captureTimes.push(i);
    }
    // 之后按视频时长每 5% 截取一次图片
    for (let i = 5; i < duration; i += intervalPercent) {
        captureTimes.push(i);
    }
    // 遍历所有需要截图的时间点
    for (const time of captureTimes) {
        const frame = await captureFrame(time); // 截取当前时间点的帧
        console.log(`截图（时间点：${time.toFixed(2)} 秒）`, frame.url);
        if (frame && frame.url) {
            // 截图成功，将截图加入到缩略图列表展示
            srcList.value.push(frame.url);
            if(time == 0) {
              //将视频第一张图片设置为默认封面图和缩略图列表封面图
              saveResourceForm.value.coverImg = frame.url;
              fileList.value.push({
                uid: '1',
                name: 'food.jpeg',
                url: frame.url,
              })
            }
        } else {
            console.error(`无法截取时间点 ${time.toFixed(2)} 的帧`);
        }
    }
};
}

//文件预览
const previewVisible = ref(false);
const previewInfo = ref({});
const preview = (row) => {
  previewVisible.value = true;
  previewInfo.value = row;

  console.log("previewInfo",previewInfo.value);
}

//文件删除
const remove = (element) => {
  ElMessageBox.confirm("是否删除该文件，删除后无法恢复？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    // const res = await deleteCommentMessages({ commentId: data.id });
    console.log("删除",element);
    
  })
}

//视频播放配置
const videoOptions = reactive({
  width: '100%',
  height: '100%',
  color: '#409eff', //主题色
  title: '测试视频播放', //视频名称
  webFullScreen: false, //网页全屏
  speed: true, //是否支持快进快退
  muted: false, //静音
  autoPlay: true, //自动播放
  loop: false, //循环播放
  mirror: false, //镜像画面
  fluid: true,
  aspectRatio: '16:9',
  control: true, //是否显示控制器
  volume: 0.5, //默认音量0-1
  notSupportedMessage: '此视频暂无法播放，请稍后再试',
  type: "m3u8",
  poster: '', //封面
  speedRate: [1.0, 1.25, 1.5, 2.0], // 可选的播放速度
  qualityLevels: ['720p', '1080p', '320p'],
  controlBtns: [
    'audioTrack', //音轨切换按钮
    'quality', //视频质量切换按钮
    'speedRate', //速率切换按钮
    'volume', //音量
    'pip', //画中画按钮
    'fullScreen' //全屏按钮
  ]
})

//表格字段
const fieldList = ref([
  {
    title: "名称",
    name: "title",
  },
  {
    title: "说明",
    name: "description",
  },
  {
    title: "大小",
    name: "fileSize",
  },
  {
    title: "类型",
    name: "fileType",
  },
  {
    title: "创建人",
    name: "createdBy",
  },
  {
    title: "创建时间",
    name: "createTime",
  },
  {
    title: "操作",
    name: "options",
    width: 150,
  },
])

onMounted(() => {
  getResourceList();
  injectCustomButton();
})
</script>

<style scoped lang="scss">
.setting-header{
  display: flex;
  align-items: center;
  p{
    font-size: 14px;
    color: $black;
  }
  span{
    color: $black_2;
  }
}
/* ::v-deep .ruifox-table-new tbody tr td .cell {
  font-size: 14px;
} */
.top-info{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  .left-tit{
    font-size: 16px;
    color: $black_2;
  }
}

.preview-dialog{
  .preview-img{
    width: 100%;
    height: auto;
  }
}

.form-img {
  height: 100px;
  width: 150px;
  border: 1px dashed $borderColor;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;

  .has-img {
    height: 100%;
    width: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      max-width: 100%;
      max-height: 100%;
    }

    span {
      display: none;
      position: absolute;
      right: 0;
      top: 0;
      background-color: $failColor;
      height: 20px;
      width: 20px;
      font-size: 18px;
      color: #fff;
    }

    &:hover {
      span {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
.img-container{

}
#custom-preview-button{
  position: fixed;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  /* height: 40px; */
  /* border-radius: 3px; */
  /* color: $black; */
  /* font-size: 16px; */
  z-index: 9999;
  /* border: 1px solid $borderColor;
  cursor: pointer; */
  /* &:hover{
    background: $mainColor;
    color: white;
  } */
}
/* ::v-deep .vue-office-pptx * {
  max-width: 100% !important;
} */

.file-name{
  height: 18px;
  line-height: 18px;
  margin-left: 10px;
  padding: 3px 8px;
  color: $black;
  font-size: 12px;
  border-radius: 2px;
  background: $weightBar;
  white-space: nowrap;     
  overflow: hidden;        
  text-overflow: ellipsis;  
  max-width: 100%;           
  flex: 1;
}
</style>